/*
 * @Descripttion :
 * @version      :
 * @Author       : zero
 * @Date         : 2021-06-03 15:27:38
 * @LastEditors  : zero
 * @LastEditTime : 2021-06-07 15:36:43
 */
import Web3 from 'web3'
import bep20 from './abi/bep20'
import BigNumber from 'bignumber.js'
import { chips } from './abi/chips'
import { chipsBet } from './abi/chipsBet'
import { develop } from './abi/develop'
import store from "@/store"
import chipsBetAbi from './abi/chipsBetAbi'
import Vue from 'vue'
import {Message} from 'element-ui';
import vue from '../main.js'
let vm = new Vue()
// import { message } from 'ant-design-vue'
const approveNum = '115792089237316195423570985008687907853269984665640564039457584007913129639935'
// 注入web3
export const web3 = (window.ethereum && new Web3(window.ethereum)) || null
// 获取已连接账户
export const Approve = (callback) => {
  if (!web3) {
    //安装metamask
    return false
  }
  if (!isbsc()) {
    switchChain()
  }
  window.ethereum.request({
    method: 'eth_requestAccounts'
  }).then(() => {
    adderss()
  }).catch(() => {
    Message({
      message: 'Please install the plugin and authorize the account',
      type: 'warning'
    })
    callback()
    //授权失败
  });
}
export let isbsc = function () {
  return Web3.utils.hexToNumber(window.ethereum.chainId) === 56
}
export const switchChain = () => {
  window.ethereum.request({
    method: 'wallet_addEthereumChain',
    params: [
      {
        chainId: web3.utils.numberToHex(56),
        chainName: 'Binance Smart Chain Mainnet',
        nativeCurrency: {
          name: 'BNB',
          symbol: 'BNB', // 2-6 characters long
          decimals: 18
        },
        rpcUrls: ['https://bsc-dataseed1.binance.org'],
        blockExplorerUrls: ['https://bscscan.com']
      }
    ]
  }).then(() => {
    // alert('2')
    // location.reload()
  }).catch(() => {
    // message.error('用户取消切换bsc链')
  })
}
// chips合约
export const chipsContract = new web3.eth.Contract(bep20, chips)
// chipsBet合约
export const chipsBetContract = new web3.eth.Contract(chipsBetAbi, chipsBet)
// 获取账户
export const adderss = () => {
  web3.eth.getAccounts().then((result) => {
    if (result.length > 0) {
      store.commit('setAccount', result[0])
    } else {
      Approve(()=>{
        
      })
    }
  }).catch(() => {
    store.commit('setAccount', '')
  });
}

// 调用web3方法前先预判
export const web3handle = async (handle) => {
  console.log(store.state.account)
  if (!web3) {
    // message.error('请安装插件并链接账户哦')
    Message({
      message: 'Please install the plugin and authorize the account',
      type: 'warning'
    })
    return false
  } else if (store.state.account == '') {
    //请先链接钱包
    return false
  } else if (!isbsc()) {
    switchChain()
    return false
  } else {
    return handle
  }
}
// 创建比赛
export const addGameInfo = async (id, startTime, guessEnd) => {
  const account = store.state.account
  console.log(account)
  try {
    const result = await chipsBetContract.methods.addGameInfo(id, startTime, guessEnd).send({
      from: account
    })
    return result
  } catch (error) {
    console.log(error)
    return false
  }
}
// 创建比赛
export const releaseGame = async (id, win) => {
  const account = store.state.account
  try {
    const result = await chipsBetContract.methods.releaseGame(id, win).send({
      from: account
    })
    return result
  } catch (error) {
    console.log(error)
    return false
  }
}

// 提取奖励
export const extractPoolEarn = async (gameId) => {
  const account = store.state.account
  try {
    const result = await chipsBetContract.methods.extractPoolEarn(gameId).send({
      from: account
    })
    return result
  } catch (error) {
    console.log(error)
    return false
  }
}
//获取用户的本场比赛的收益

export const queryPoolEarn = async (id) => {
  const account = store.state.account
  try {
    const result = await chipsBetContract.methods.queryPoolEarn(id, account).call()
    return result
  } catch (error) {
    console.log(error)
  }
}
// 投注
export const poolBet = async (amount, gameId, betPoolInID) => {
  const account = store.state.account
  try {
    const result = await chipsBetContract.methods.poolBet(amount, gameId, betPoolInID).send({
      from: account
    })
    return result
  } catch (error) {
    console.log(error)
  }
}
//获取余额
export const getBlance = (callBack) => {
  const account = store.state.account
  console.log(account)
  chipsContract.methods.balanceOf(account).call().then((result) => {
    console.log(result)
    store.commit('setBlance', web3.utils.fromWei(result))
    callBack(web3.utils.fromWei(result))
  }).catch(() => {
    //请授权获取余额
    // Message({
    //   message: '请授权获取余额',
    //   type: 'warning'
    // })
    
  });
}
// 查询赛事奖池
export const gamePoolInfoMapping = async (id) => {
  // const account = store.state.account
  try {
    const result = await chipsBetContract.methods.gamePoolInfoMapping(id).call()
    return result
  } catch (error) {
    console.log(error)
  }
}
//查询该用户的本场记录
export const userInfoMapping = async (gameId) => {
  const account = store.state.account
  try {
    console.log(account, gameId)
    const result = await chipsBetContract.methods.userInfoMapping(account, gameId).call()
    return result
  } catch (error) {
    console.log(error)
  }
}
// 撤资
export const withdrawBetPool = async (gameId, betPooInId) => {
  const account = store.state.account
  try {
    const result = await chipsBetContract.methods.withdrawBetPool(gameId, betPooInId).send({
      from: account
    })
    return result
  } catch (error) {
    return false
    console.log(error)
  }
}
// 授权chips给chipsBet
export const ApproveChipsToChipsBet = async (callback,errorback) => {
  if (!(await chipsContract.methods.allowance(store.state.account, chipsBet).call() > 0)) {
    console.log(new BigNumber(approveNum).toFixed(0).toString())
    chipsContract.methods.approve(chipsBet, new BigNumber(approveNum).toFixed(0).toString())
      .send({ from: store.state.account })
      .on('transactionHash', function (hash) {
        // 交易hash
        console.log(hash)
      })
      .on('receipt', function () {
        callback()
      }).on('error', function (error) {
        console.log(error)
        // Message({
        //   Message: 'Refuse Authorization',
        //   type: 'warning'
        // })
        errorback()
      })
      .catch((error) => {
        console.log(error)
        Message({
          message: 'Refuse Authorization',
          type: 'warning'
        })
        errorback()
      })
  } else {
    callback()
  }
}

//节流函数
export const throttle = function (fn, delay) {
  var timer;
  return function () {
    var _this = this;
    var args = arguments;
    if (timer) {
      return;
    }
    timer = setTimeout(function () {
      fn.apply(_this, args);
      timer = null; // 在delay后执行完fn之后清空timer，此时timer为假，throttle触发可以进入计时器
    }, delay)
  }
}

//防抖
export const debounce = (fn, delay) => {
  var timer; // 维护一个 timer
  return function () {
    var _this = this; // 取debounce执行作用域的this
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      fn.apply(_this, args); // 用apply指向调用debounce的对象，相当于_this.fn(args);
    }, delay);
  };
}